package cn.eweb.ttkt;

import java.io.BufferedInputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

import org.apache.http.util.ByteArrayBuffer;
import org.apache.http.util.EncodingUtils;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.provider.Settings.Secure;
import android.util.Log;

public class PushReceiver extends BroadcastReceiver {

	/*要接收的intent源*/
    static final String ACTION = "android.intent.action.BOOT_COMPLETED";
	
	@Override
	public void onReceive(Context context, Intent intent) {
		if (intent.getAction().equals(ACTION)){
			startPushService(context);
        }
		
	}
	
	private void startPushService(Context context){
    	SharedPreferences p = context.getSharedPreferences(PushService.TAG, Context.MODE_PRIVATE);
  	  	boolean started = p.getBoolean(PushService.PREF_STARTED, false);
  	  	if(!started){
  	  		final String deviceId = Secure.getString(context.getContentResolver(), Secure.ANDROID_ID);
	  	  	final String push_url = context.getString(R.string.device_register_url)+"&device="+deviceId;
  	  		Editor editor = p.edit();
	    	editor.putString(PushService.PREF_DEVICE_ID, deviceId);
	    	editor.commit();
	    	new Thread() {
				@Override
				public void run() {
					super.run();
					try {  
				    	URL myURL = new URL(push_url);  
			            // 打开URL链接  
			            URLConnection ucon = myURL.openConnection();
			            // 使用InputStream，从URLConnection读取数据  
			            InputStream is = ucon.getInputStream();  
			            BufferedInputStream bis = new BufferedInputStream(is);  
			            // 用ByteArrayBuffer缓存  
			            ByteArrayBuffer baf = new ByteArrayBuffer(50);  
			            int current = 0;  
			            while ((current = bis.read()) != -1) {  
			                baf.append((byte) current);  
			            }  
			            // 将缓存的内容转化为String,用UTF-8编码  
			            String result = EncodingUtils.getString(baf.toByteArray(), "UTF-8");
			            Log.e("test", result);
			        } catch (Exception e) {  
			            e.printStackTrace();
			        }  
				}
			}.start();
			PushService.actionStart(context);
  	  	}
    }

}
